﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AxVSCLIENTOCXLib;
using System.Configuration;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;
using DevComponents.AdvTree;
using dataSendModel.Util;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using dataSendModel;
using dataSend.ToolForm;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Reflection;
using dataSendDal.Util;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;


namespace dataSend
{
    public partial class MainForm : DevComponents.DotNetBar.Office2007Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        #region 声明字段
        private delegate void setLogHandle(string text, string exMsg);
        //private delegate void SetControl(ButtonX btn);
        private TcpClient clientCollect = null;  //9000端口
        private TcpClient clientOcx = null; //9988端口
        private TcpClient clientGps = null;
        private ManualResetEvent connectDone = new ManualResetEvent(false);
        private logger log = null;
        private Dictionary<string, string> readerDic = new Dictionary<string, string>();
        private Dictionary<string, string> gpsDic = new Dictionary<string, string>();
        #endregion

        #region 读取配置文件
        string supplierIp = ConfigurationManager.AppSettings["supplierIp"];
        string supplierPort = ConfigurationManager.AppSettings["supplierPort"];
        string supplierUser = ConfigurationManager.AppSettings["supplierUser"];
        string supplierPass = ConfigurationManager.AppSettings["supplierPass"];
        string collectionIp = ConfigurationManager.AppSettings["collectionIp"];
        string collectionPort = ConfigurationManager.AppSettings["collectionPort"];
        string ocxServerIp = ConfigurationManager.AppSettings["ocxServerIp"];
        string ocxServerPort = ConfigurationManager.AppSettings["ocxServerPort"];
        string gpsServerIp = ConfigurationManager.AppSettings["gpsServerIp"];
        string gpsServerPort = ConfigurationManager.AppSettings["gpsServerPort"];
        #endregion

        #region 生成树
        /// <summary>
        /// 读取车辆树
        /// </summary>
        public void getDevice()
        {
            DataSet ds = null;
            try
            {
                using (SqlDBHelper db = new SqlDBHelper())
                {
                    string sql = "select f.code,f.videoEquiCode,f.gpsEquiCode,r.code AS readerId from t_frontequipment f,t_reader r where r.id = f.readerId";
                    ds = db.getDataSet(sql);
                }
                if (ds.Tables[0].Rows.Count == 0)
                {
                    setLog("获取设备列表失败！", string.Empty);
                    return;
                }
            }
            catch (Exception ex)
            {
                setLog("获取设备列表失败！", ex.Message);
                return;
            }

            tvDevice.Nodes.Clear();
            short iDevCount = 0;
            string strDevIDs = string.Empty;
            strDevIDs = this.vsOcx.GetDevList(ref iDevCount);
            string[] deviDs = strDevIDs.Split('\t');
            string[] deviceSplit;
            List<Device> deviceList = new List<Device>();
            Device device = null;
            Node node = null;  //二级
            Node tool = new Node("设备列表");  //总级
            tool.Expand();
            int index = -1;

            if (strDevIDs.Equals(""))
            {
                setLog("获取设备列表失败！", string.Empty);
                return;
            }

            foreach (string item in deviDs)
            {
                if (item.Trim() != "")
                {
                    index++;
                    deviceSplit = item.Split('&');
                    node = new Node();
                    node.Expand();
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        if (dr["videoEquiCode"].ToString().Equals(deviceSplit[0]))  //判断设备ID是否相等
                        {
                            int readerId = int.Parse(dr["readerId"].ToString());
                            string gpsId = dr["gpsEquiCode"].ToString();
                            device = new Device(deviceSplit[0], deviceSplit[1], int.Parse(deviceSplit[2]), readerId, gpsId);
                            node.Name = device.Id;
                            node.Text = dr["code"].ToString();
                            device.Index = index;

                            if (device.State == 1)
                            {
                                string[] deviceInfo = this.vsOcx.GetDevInfoEx(device.Id).Split('&');
                                device.Ip = deviceInfo[1];
                                device.Count = int.Parse(deviceInfo[2]);
                                for (int i = 3; i < deviceInfo.Length - 1; i++)
                                {
                                    if (deviceInfo[i].Trim() != "")
                                    {
                                        Node nodeClind = new Node(deviceInfo[i]);  //三级
                                        device.Channels.Add(deviceInfo[i]);
                                        nodeClind.Tag = i - 3;
                                        node.Nodes.Add(nodeClind); //二级加三级
                                    }
                                }
                                node.Tag = device;
                            }
                            deviceList.Add(device);
                            node.ContextMenu = this.contextMenuStrip1;
                            tool.Nodes.Add(node);  //总树加二级
                        }
                    }

                }
            }
            tvDevice.Nodes.Add(tool); //控件加总树
        }
        #endregion

        #region 窗体加载
        private void MainForm_Load(object sender, EventArgs e)
        {
            log = new logger();
            this.cboPort.SelectedIndex = 0;
            short ret = vsOcx.Login(supplierIp, short.Parse(supplierPort), supplierUser, supplierPass);
        } 
        #endregion

        #region 创建连接
        /// <summary>
        /// 连接采集上行9000端口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect9000_Click(object sender, EventArgs e)
        {
            if ((clientCollect != null) && (clientCollect.Connected))
            {
                DisConnect(clientCollect);
            }
            else
            {
                try
                {
                    setLog("开始连接采集服务器上行", string.Empty);
                    clientCollect = new TcpClient();
                    Connect(clientCollect, collectionIp, collectionPort);
                    setLog("连接成功！" + clientCollect.Client.RemoteEndPoint, string.Empty);
                }
                catch (Exception ex)
                {
                    setLog("连接采集服务器上行失败", ex.Message);
                }
            }
            setBtnStatus(btnConnect9000);
        }


        /// <summary>
        /// 连接采集下行9988端口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect9988_Click(object sender, EventArgs e)
        {

            if (((clientOcx != null) && (clientOcx.Connected))||this.collectTime.Enabled==true)
            {
                DisConnect(clientOcx);
                this.collectTime.Stop();
            }
            else
            {
                try
                {
                    setLog("开始连接采集服务器下行", string.Empty);
                    clientOcx = new TcpClient();
                    Connect(clientOcx, ocxServerIp, ocxServerPort);
                    setLog("连接成功！" + clientOcx.Client.RemoteEndPoint, string.Empty);
                    if (clientOcx != null && clientOcx.Connected)
                    {
                        collectRead(clientOcx);
                        setLog("采集数据中。。。。", string.Empty);
                    }

                }
                catch (Exception ex)
                {

                    setLog("连接采集服务器下行失败！", ex.Message);
                }
            }
            setBtnStatus(btnConnect9988);
        }

        /// <summary>
        /// 连接gps服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnectGps_Click(object sender, EventArgs e)
        {
            if (((clientGps != null) && (clientGps.Connected))||this.gpsTime.Enabled == true)
            {
                DisConnect(clientGps);
                this.gpsTime.Enabled = false;
            }
            else
            {
                try
                {
                    setLog("开始连接GPS服务器", string.Empty);
                    clientGps = new TcpClient();
                    Connect(clientGps, gpsServerIp, gpsServerPort);
                    setLog("连接成功！" + clientGps.Client.RemoteEndPoint, string.Empty);
                    if (clientGps != null && clientGps.Connected)
                    {
                        gpsRead(clientGps);
                        setLog("GPS数据接收中。。。。", string.Empty);
                        if (gpsDic != null && gpsDic.Keys.Count > 0)
                        {
                            foreach (string gpsId in gpsDic.Keys)
                            {
                                new Thread(x =>
                                {
                                    clientGps.Client.Send(CodeConvert.stringToHex(CodeConvert.getGpsRegist(gpsId)));
                                }).Start();
                                
                            }
                        }
                    }
                }
                catch (Exception ex)
                {

                    setLog("连接GPS服务器失败！", ex.Message);
                }
            }
            setBtnStatus(btnConnectGps);

        }
        #endregion

        #region Tcpclient异步连接接收

        // 异步连接
        private void Connect(TcpClient tcp, string ip, string port)
        {
            if ((tcp.Client == null) || (!tcp.Connected))
            {

                tcp.ReceiveTimeout = 10;

                connectDone.Reset();

                tcp.BeginConnect(ip, int.Parse(port),
                    new AsyncCallback(ConnectCallback), tcp);

                connectDone.WaitOne();

            }
        }

        // 异步连接的回调函数
        private void ConnectCallback(IAsyncResult ar)
        {
            connectDone.Set();
            TcpClient t = (TcpClient)ar.AsyncState;

            if (t.Connected)
            {
                t.EndConnect(ar);
            }
        }


        // 断开连接
        private void DisConnect(TcpClient tcp)
        {
            if ((tcp != null) && (tcp.Connected))
            {
                tcp.GetStream().Close();
                tcp.Close();
            }
        }


        // 异步读取9988采集服务器数据
        private void collectRead(TcpClient tcp)
        {
            StateObject state = new StateObject();
            state.client = tcp;
            NetworkStream stream = tcp.GetStream();

            if (stream.CanRead)
            {
                try
                {
                    IAsyncResult ar = stream.BeginRead(state.buffer, 0, StateObject.BufferSize,
                            new AsyncCallback(collectReadCallBack), state);
                }
                catch (Exception e)
                {
                    setLog("基站数据读取失败！", e.Message);
                }
            }
        }


        // 异步读取9988采集服务器回调函数
        private void collectReadCallBack(IAsyncResult ar)
        {

            try
            {
                StateObject state = (StateObject)ar.AsyncState;
                //主动断开时
                if ((state.client == null) || (!state.client.Connected))
                {
                    return;
                }
                int numberOfBytesRead;
                NetworkStream mas = state.client.GetStream();

                numberOfBytesRead = mas.EndRead(ar);
                state.totalBytesRead += numberOfBytesRead;


                if (numberOfBytesRead > 0)
                {
                    byte[] dd = new byte[numberOfBytesRead];
                    Array.Copy(state.buffer, 0, dd, 0, numberOfBytesRead);
                    receiveData(dd, 485);
                    mas.BeginRead(state.buffer, 0, StateObject.BufferSize,
                            new AsyncCallback(collectReadCallBack), state);
                }
                else
                {
                    //被动断开时                
                    //mas.Close();
                    //state.client.Close();
                    //DisConnect(clientCollect);
                    //setBtnStatus(btnConnect9988);
                    //mas = null;
                    //state = null;
                }
            }
            catch (IOException ex)
            {
                setLog("基站数据回调读取失败！", ex.Message);
                setLog("与采集服务器下行断开连接,自动连接中。。", string.Empty);
                this.Invoke(new EventHandler(delegate
                {
                    this.collectTime.Start();
                }));
                
            }
        }

        //9988采集服务器自动连接
        private void collectTime_Tick(object sender, EventArgs e)
        {
            if ((clientOcx != null) && (clientOcx.Connected))
            {
                collectTime.Stop();
            }
            else
            {
                try
                {
                    clientOcx = new TcpClient();
                    Connect(clientOcx, ocxServerIp, ocxServerPort);
                    if (clientOcx != null && clientOcx.Connected)
                    {
                        setLog("连接成功！" + clientOcx.Client.RemoteEndPoint, string.Empty);
                        collectRead(clientOcx);
                        setLog("采集数据接收中。。。。", string.Empty);
                    }
                    else
                    {
                        setLog("采集服务器连接中", string.Empty);
                    }

                }
                catch (IOException ex)
                {

                }
            }
        }


        // 异步读取gps服务器数据
        private void gpsRead(TcpClient tcp)
        {
            StateObject state = new StateObject();
            state.client = tcp;
            NetworkStream stream = tcp.GetStream();

            if (stream.CanRead)
            {
                try
                {
                    IAsyncResult ar = stream.BeginRead(state.buffer, 0, StateObject.BufferSize,
                            new AsyncCallback(gpsReadCallBack), state);
                }
                catch (Exception e)
                {
                    setLog("GPS数据读取失败", e.Message);
                }
            }
        }


        // 异步读取gps服务器数据回调函数
        private void gpsReadCallBack(IAsyncResult ar)
        {

            try
            {
                StateObject state = (StateObject)ar.AsyncState;
                //主动断开时
                if ((state.client == null) || (!state.client.Connected))
                {
                    return;
                }
                int numberOfBytesRead;
                NetworkStream mas = state.client.GetStream();

                numberOfBytesRead = mas.EndRead(ar);
                state.totalBytesRead += numberOfBytesRead;

                if (numberOfBytesRead > 0)
                {
                    byte[] dd = new byte[numberOfBytesRead];
                    Array.Copy(state.buffer, 0, dd, 0, numberOfBytesRead);
                    receiveData(dd, 232);
                    mas.BeginRead(state.buffer, 0, StateObject.BufferSize,
                            new AsyncCallback(gpsReadCallBack), state);
                }
                else
                {
                    //被动断开时                
                    //mas.Close();
                    //state.client.Close();
                    //setLog("与GPS服务器连接断开,自动连接中。。", string.Empty);
                    //DisConnect(clientGps);
                    //setBtnStatus(btnConnectGps);
                    ////gpsTime.Enabled = true;
                    //mas = null;
                    //state = null;
                }
            }
            catch (Exception ex)
            {
                setLog("GPS数据回调读取失败！", ex.Message);
                setLog("与GPS服务器连接断开,自动连接中。。", string.Empty);
                this.Invoke(new EventHandler(delegate
                {
                    this.gpsTime.Enabled = true;
                }));
            }
        }

        //gps服务器自动连接
        private void gpsTime_Tick(object sender, EventArgs e)
        {
            if ((clientGps != null) && (clientGps.Connected))
            {
                gpsTime.Enabled = false;
            }
            else
            {
                try
                {
                    clientGps = new TcpClient();
                    Connect(clientGps, gpsServerIp, gpsServerPort);
                    if (clientGps != null && clientGps.Connected)
                    {
                        setLog("连接成功！" + clientGps.Client.RemoteEndPoint, string.Empty);
                        gpsRead(clientGps);
                        setLog("GPS数据接收中。。。。", string.Empty);
                    }
                }
                catch (Exception ex)
                {
                    setLog("GPS服务器连接中。。", ex.Message);
                }
            }
        }



        /// <summary>
        /// listbox控件自动向下滚动
        /// </summary>
        /// <param name="lb"></param>
        /// <param name="text"></param>
        private void listBoxAutoScroll(ListBox lb, string text)
        {
            bool scroll = false;
            if (lb.TopIndex == lb.Items.Count - (int)(lb.Height / lb.ItemHeight))
            {
                scroll = true;
            }
            lb.Items.Add(text);
            if (scroll)
            {
                lb.TopIndex = lb.Items.Count - (int)(lb.Height / lb.ItemHeight);
            }
        }

        #endregion

        string rdata = string.Empty;
        string result = string.Empty;
        string sendMsg = string.Empty;
        string gpsAdress = string.Empty;
        string readerAdress = string.Empty;
        string equId = string.Empty;
        /// <summary>
        ///  异步控件显示接收数据并下行发送
        /// </summary>
        /// <param name="data"></param>
        private void receiveData(byte[] data, int type)
        {
            rdata = CodeConvert.byteToHexStr(data);
            short ret = 0;
            if (type == 485) //基站
            {
                readerAdress = CodeConvert.getReaderAdress(rdata);
                equId = readerDic[readerAdress];
                if (readerAdress.Equals("") || equId.Equals(""))  //找不到地址码或视频设备ID时提示
                {
                    setLog("视频设备ID：" + equId + ",基站地址码：" + readerAdress + "(下行失败)", string.Empty);
                    return;
                }
                ret = this.vsOcx.SendComTransmitMsgEx(equId, short.Parse("1"), rdata, short.Parse(rdata.Length.ToString()));
                result = ret == 0 ? "下行发送成功" : "下行发送失败";
                tbCollectData.Invoke(new EventHandler(delegate
                {
                    string msg = ">>" + DateTime.Now.ToString() + " " + rdata + " " + result;
                    tbCollectData.AppendText(msg + Environment.NewLine);
                    log.readerWrite(msg);
                }));
            }
            else //GPS
            {
                if (CodeConvert.checkGpsCode(rdata)) //检查是否含有65指令
                {
                    return;
                }
                sendMsg = CodeConvert.sendGpsMsg(rdata);
                gpsAdress = CodeConvert.getGpsAdress(sendMsg);
                equId = gpsDic[gpsAdress];
                if (gpsAdress.Equals("") || equId.Equals(""))  //找不到地址码或视频设备ID时提示
                {
                    setLog("视频设备ID：" + equId + ",GPS身份码：" + gpsAdress + "(下行失败)", string.Empty);
                    return;
                }

                ret = this.vsOcx.SendComTransmitMsgEx(equId, short.Parse("0"), sendMsg, short.Parse(sendMsg.Length.ToString()));
                result = ret == 0 ? "下行发送成功" : "下行发送失败";
                tbGpsData.Invoke(new EventHandler(delegate
                {
                    string msg = ">>" + DateTime.Now.ToString() + " " + sendMsg + " " + result;
                    tbGpsData.AppendText(msg + Environment.NewLine);
                    log.gpsWrite(msg);
                }));
            }


        }


        StringBuilder sbReader = new StringBuilder();
        StringBuilder sb = new StringBuilder();
        Regex regex_1 = new Regex("((1002)\\w*?[^(1003)]\\w*?)(1002)");
        Regex regex_2 = new Regex("((1002)\\w+?(1003))");
        Match match = null;
        string gpsResult = string.Empty;  //得到的gps字符串
        string sendRedMsg = string.Empty; //最后发送的reader数据
        /// <summary>
        /// 数据接收事件 数据上行发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void vsOcx_ComTransmitMsg(object sender, _DVSClientOCXEvents_ComTransmitMsgEvent e)
        {
            if (e.iMsgType == 4867)
            {
                if (clientCollect != null && clientCollect.Connected)
                {
                    sbReader.Append(e.csMsg.Replace(" ", ""));
                    sbReader.Replace("5AA5", ",");
                    string[] strs = sbReader.ToString().Split(',');
                    if (!strs[0].Equals(""))
                    {
                        sbReader.Replace(strs[0], "");
                    }

                    for (int i = 1; i < strs.Length; i++)
                    {
                        sendRedMsg = "5AA5" + strs[i];
                        //sendData(sendRedMsg, 485); //测试波特
                        if (CodeConvert.checkReaderCode(sendRedMsg))
                        {
                            aboutEquAdress(e.csDevID, sendRedMsg, e.iMsgType); //加到集合里面
                            sendData(sendRedMsg, 485);//原来的
                            clientCollect.Client.Send(CodeConvert.stringToHex(sendRedMsg));  //发到9000端口
                        }
                        sbReader.Replace("," + strs[i], "");
                    }

                }
            }
            else
            {
                try
                {
                    sb.Append(e.csMsg);
                    match = regex_1.Match(sb.ToString());
                    if (match.Success)
                    {
                        gpsResult = match.Groups[1].Value;
                        sb.Replace(gpsResult, "");
                    }

                    match = regex_2.Match(sb.ToString());
                    if (match.Success)
                    {
                        gpsResult = match.Groups[1].Value;

                        //sendData(gpsResult, 232);//测试波特

                        byte[] content = CodeConvert.getGpsMsg(gpsResult); //判断帧结构是否合格并取得内容

                        if (content != null && content.Length > 0)
                        {
                            if (clientGps != null && clientGps.Connected)
                            {
                                gpsResult = gpsResult.Replace("1010","10");
                                aboutEquAdress(e.csDevID, gpsResult, e.iMsgType); //加到集合里面
                                clientGps.Client.Send(content);
                                sendData(gpsResult, 232);//原来的
                            }
                        }
                        sb.Replace(gpsResult, "");
                    }

                }
                catch (Exception ex)
                {
                    setLog("GPS上行接收出错", ex.Message);
                }
            }
        }

        #region 显示发送服务器数据
        private void sendData(string data, int type)
        {
            string msg = string.Empty;
            if (type == 485)
            {
                tbCollectData.Invoke(new EventHandler(delegate
                {
                    msg = ">>" + DateTime.Now.ToString() + " " + data + " 上行服务器";
                    tbCollectData.AppendText(msg + Environment.NewLine);
                    log.readerWrite(msg);
                }));
            }
            else
            {
                tbGpsData.Invoke(new EventHandler(delegate
                {
                    msg = ">>" + DateTime.Now.ToString() + " " + data + " 上行服务器";
                    tbGpsData.AppendText(msg + Environment.NewLine);
                    log.gpsWrite(msg);
                }));
            }


        }
        #endregion

        #region 把GPS或者基站地址码放进集合
        string readerKey = string.Empty;
        string gpsKey = string.Empty;
        private void aboutEquAdress(string equId, string recStr, int msgType)
        {
            if (msgType == 4867)
            {
                readerKey = CodeConvert.getReaderAdress(recStr);
                if (!readerDic.ContainsKey(readerKey))
                {
                    readerDic.Add(readerKey, equId);
                    setLog("视频设备ID：" + equId + ",基站地址码：" + readerKey + "(上行)", string.Empty);
                }
            }
            else
            {
                gpsKey = CodeConvert.getGpsAdress(recStr);
                if (!gpsDic.ContainsKey(gpsKey))
                {
                    gpsDic.Add(gpsKey, equId);
                    setLog("视频设备ID：" + equId + ",GPS身份码：" + gpsKey + "(上行)", string.Empty);
                    if (clientGps != null && clientGps.Connected)//向GPS服务器发送注册信息
                    {
                        new Thread(x =>
                        {
                            clientGps.Client.Send(CodeConvert.stringToHex(CodeConvert.getGpsRegist(gpsKey)));
                        }).Start();
                    }
         
                }
            }
        } 
        #endregion

        #region 设置相关

        /// <summary>
        /// 异步tbLog显示日志
        /// </summary>
        /// <param name="text"></param>
        public void setLog(string text, string exMsg)
        {
            if (tbLog.InvokeRequired)
            {
                setLogHandle d = new setLogHandle(setLog);
                this.tbLog.Invoke(d, new object[] { text, exMsg });
            }
            else
            {
                string msg = ">>" + DateTime.Now.ToString() + " " + text;
                this.tbLog.AppendText(msg + Environment.NewLine);
                log.infoWrite(msg + " " + exMsg);
            }
        }

        /// <summary>
        /// 验证是否点击到设备
        /// </summary>
        /// <returns></returns>
        private bool validateRoot()
        {
            if (this.tvDevice.SelectedNode == null || this.tvDevice.SelectedNode.Parent == null || this.tvDevice.SelectedNode.LastNode == null)
            {
                MessageBoxEx.Show("请选择设备", "系统提示");
                return false;
            }
            return true;
        }

        /// <summary>
        /// 设置控件状态
        /// </summary>
        /// <param name="btn"></param>
        private void setBtnStatus(ButtonX btn)
        {
            //if (btnConnect9988.InvokeRequired)
            //{
            //    this.Invoke(new SetControl(setBtnStatus));
            //}
            int con = 0;
            string[] constr = new string[2];
            if (btn.Tag.ToString().Equals("上行"))
            {
                con = ((clientCollect == null) || (!clientCollect.Connected)) ? 0 : 1;
                constr[0] = "连接采集上行";
                constr[1] = "断开采集上行";
            }
            if (btn.Tag.ToString().Equals("下行"))
            {
                con = ((clientOcx == null) || (!clientOcx.Connected)) ? 0 : 1;
                constr[0] = "连接采集下行";
                constr[1] = "断开采集下行";
            }

            if (btn.Tag.ToString().Equals("gps"))
            {
                con = ((clientGps == null) || (!clientGps.Connected)) ? 0 : 1;
                constr[0] = "连接GPS服务";
                constr[1] = "断开GPS服务";

            }
            
            btn.Invoke(new EventHandler(delegate
            {
                btn.Text = constr[con];
            }));

            if (con == 0)
            {
                setLog(constr[1], string.Empty);
            }

        }

        /// <summary>
        /// 串口设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPortSet_Click(object sender, EventArgs e)
        {
            try
            {
                //判断设备是否选中
                if (validateRoot())
                {
                    short type = short.Parse(this.cboPort.SelectedItem.ToString() == "232" ? "0" : "1");
                    string result = this.vsOcx.GetComParamEx(this.tvDevice.SelectedNode.Name, type);
                    if (result.Contains(","))
                    {
                        //弹出串口设置窗口
                        PortSet ps = new PortSet(result, this.tvDevice.SelectedNode.Name, type, this);
                        ps.Show();
                    }
                    else
                    {
                        MessageBoxEx.Show("串口获取失败！", "系统提示");
                    }
                }
            }
            catch (Exception ex)
            {

                MessageBoxEx.Show("串口获取失败！" + ex, "系统提示");
            }
        }

        /// <summary>
        /// 上行条件获取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpSendGet_Click(object sender, EventArgs e)
        {
            if (validateRoot())
            {
                string result = this.vsOcx.GetTYParamEx(this.tvDevice.SelectedNode.Name, 0);
                if (result.Contains(","))
                {
                    string[] res = result.Split(',');
                    tbTime.Text = res[0];
                    tbLength.Text = res[1];
                }
            }

        }

        /// <summary>
        /// 上行条件设置 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpSendSet_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbTime.Text) || string.IsNullOrEmpty(tbLength.Text))
            {
                return;
            }
            if (validateRoot())
            {
                short result = this.vsOcx.SetTYParamEx(this.tvDevice.SelectedNode.Name, 0, short.Parse(tbTime.Text), short.Parse(tbLength.Text));
                if (result >= 0)
                {
                    MessageBoxEx.Show("设置成功！", "系统提示");
                }
                else
                {
                    MessageBoxEx.Show("设置失败！", "系统提示");
                }
            }
        }

        /// <summary>
        /// 下行条件获取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDownSendGet_Click(object sender, EventArgs e)
        {
            if (validateRoot())
            {
                string result = this.vsOcx.GetTYParamEx(this.tvDevice.SelectedNode.Name, 1);
                if (result.Contains(","))
                {
                    string[] res = result.Split(',');
                    tbTime.Text = res[0];
                    tbLength.Text = res[1];
                }
            }
        }

        /// <summary>
        /// 下行条件设置 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDownSendSet_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbTime.Text) || string.IsNullOrEmpty(tbLength.Text))
            {
                return;
            }
            if (validateRoot())
            {
                short result = this.vsOcx.SetTYParamEx(this.tvDevice.SelectedNode.Name, 1, short.Parse(tbTime.Text), short.Parse(tbLength.Text));
                if (result >= 0)
                {
                    MessageBoxEx.Show("设置成功！", "系统提示");
                }
                else
                {
                    MessageBoxEx.Show("设置失败！", "系统提示");
                }
            }
        }


        /// <summary>
        /// 设备上下线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void vsOcx_DevOnOff(object sender, _DVSClientOCXEvents_DevOnOffEvent e)
        {
            if (e.bStatus == 1)
            {
                setLog("设备上线,设备ID：" + e.csDevID, string.Empty);
            }
            else
            {
                setLog("设备下线,设备ID：" + e.csDevID, string.Empty);
            }
            Waitting wt = new Waitting(300);
            wt.showWatting();
            new Thread(new ThreadStart(getDevice)).Start();

        }

        /// <summary>
        /// 服务器掉线通知
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void vsOcx_ServerOffLine(object sender, _DVSClientOCXEvents_ServerOffLineEvent e)
        {
            if (e.bOnLine == 1)
            {
                setLog("服务器已下线", string.Empty);
            }
        }

        /// <summary>
        /// 登录反馈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void vsOcx_LoginResult(object sender, _DVSClientOCXEvents_LoginResultEvent e)
        {
            if (e.iRet == 0)
            {
                setLog("登录视频服务器成功", string.Empty);
                Waitting wt = new Waitting(300);
                wt.showWatting();
                new Thread(new ThreadStart(getDevice)).Start();
            }
            else
            {
                setLog("登录视频服务器失败", string.Empty);
            }
        }

        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            log.InfoSw.Close();
            log.GpsSw.Close();
            log.ReaderSw.Close();
            Application.Exit();
        }

        /// <summary>
        /// 鼠标右键基站参数设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiReaderSet_Click(object sender, EventArgs e)
        {
            object obj = tvDevice.SelectedNode.Tag;
            if (obj != null)
            {
                Device dev = (Device)obj;
                DataTable dt = null;
                try
                {
                    using (SqlDBHelper db = new SqlDBHelper())
                    {
                        string sql = "select r.id,r.sensitivity1,r.sensitivity2,r.temperature,r.uploadTimeInterval,r.recordTime from t_readerstate r where r.id = ?readerId";
                        dt = db.GetTable(sql, new MySqlParameter("?readerId", dev.ReaderId));
                    }
                    string readerAdreess = string.Empty;  //找出地址码
                    foreach (string item in readerDic.Keys)
                    {
                        if (dev.Id.Equals(readerDic[item]))
                        {
                            readerAdreess = item;
                        }
                    }
                    if (dt!=null && dt.Rows.Count != 0 && !readerAdreess.Equals(""))
                    {
                        ReaderState rs = new ReaderState();
                        rs.ReaderId = dt.Rows[0]["id"].ToString();
                        rs.Sensitivity1 = dt.Rows[0]["sensitivity1"] == DBNull.Value ? 0 : int.Parse(dt.Rows[0]["sensitivity1"].ToString());
                        rs.Sensitivity2 = dt.Rows[0]["sensitivity2"] == DBNull.Value ? 0 : int.Parse(dt.Rows[0]["sensitivity2"].ToString());
                        rs.Temperature = dt.Rows[0]["temperature"] == DBNull.Value ? 0 : int.Parse(dt.Rows[0]["temperature"].ToString());
                        rs.UploadTime = dt.Rows[0]["uploadTimeInterval"] == DBNull.Value ? 0 : int.Parse(dt.Rows[0]["uploadTimeInterval"].ToString());
                        if (dt.Rows[0]["recordTime"] != DBNull.Value) rs.RecordTime = DateTime.Parse(dt.Rows[0]["recordTime"].ToString());
                        ReaderSetForm rsf = new ReaderSetForm(dev.Id, rs, readerAdreess, this);
                        rsf.Show();
                    }
                    else
                    {
                        MessageBoxEx.Show("没有该基站参数值！", "系统提示");
                    }
                }
                catch (Exception ex)
                {
                    setLog("获取基站参数失败！", ex.Message);
                }
            }
        }

        #endregion

        #region 不知是啥
        private void openOrHide_Click(object sender, EventArgs e)
        {
            if (this.sendTouChuan.Visible == true)
            {
                this.sendTouChuan.Visible = false;
            }
            else
            {
                this.sendTouChuan.Visible = true;
            }
        } 
        #endregion

        #region 单一透传
        private void sendTouChuan_Click(object sender, EventArgs e)
        {
            if (validateRoot())
            {
                short itype = 0;
                if (cboPort.SelectedItem.ToString().Equals("485"))
                {
                    itype = 1;
                }
                SendForm sf = new SendForm(this.tvDevice.SelectedNode.Name, itype, this);
                sf.ShowDialog();
            }
        } 
        #endregion

        private void btnResetDev_Click(object sender, EventArgs e)
        {
            Waitting wt = new Waitting(300);
            wt.showWatting();
            new Thread(new ThreadStart(getDevice)).Start();
        }

    }

    #region stateObject类
    internal class StateObject
    {
        public TcpClient client = null;
        public int totalBytesRead = 0;
        public const int BufferSize = 1024;
        public string readType = null;
        public byte[] buffer = new byte[BufferSize];
        public StringBuilder messageBuffer = new StringBuilder();
    }
    #endregion

}
